<template>
  <div class="asset-list-container">
    <!-- 搜索表单 -->
    <el-form
      :model="searchForm"
      class="search-form"
      style="width: 100%; display: flex; flex-wrap: wrap; align-items: center"
    >
      <el-form-item label="项目名称" style="flex: 1">
        <el-input
          v-model="searchForm.project"
          placeholder="项目名称"
          clearable
        />
      </el-form-item>
      <el-form-item label="资产编号" style="flex: 1">
        <el-input
          v-model="searchForm.assetCode"
          placeholder="资产编号"
          clearable
        />
      </el-form-item>
      <el-form-item label="资产地址" style="flex: 1">
        <el-input
          v-model="searchForm.address"
          placeholder="资产地址"
          clearable
        />
      </el-form-item>
      <el-form-item label="资产数量" style="flex: 1">
        <el-input
          v-model="searchForm.countMin"
          placeholder="最小值"
          style="width: 40%"
        />
        <span style="margin: 0 8px">-</span>
        <el-input
          v-model="searchForm.countMax"
          placeholder="最大值"
          style="width: 40%"
        />
      </el-form-item>
      <el-form-item label="预警类型" style="flex: 1">
        <el-select
          v-model="searchForm.warningType"
          placeholder="预警类型"
          clearable
        >
          <el-option label="全部" value="" />
          <el-option label="价格比对" value="价格比对" />
          <el-option label="合同合规" value="合同合规" />
          <el-option label="空置监测" value="空置" />
          <!-- <el-option label="无合同" value="无合同" /> -->
        </el-select>
      </el-form-item>
      <el-form-item style="flex: 0 0 auto; margin-left: auto">
        <el-button type="primary" @click="handleSearch">搜索</el-button>
      </el-form-item>
    </el-form>

    <!-- 数据表格 -->
    <el-table
      :data="tableData"
      style="width: 100%"
      border
      stripe
      v-loading="loading"
    >
      <el-table-column
        prop="project"
        label="项目名称"
        show-overflow-tooltip
        fixed="left"
        width="150"
      />

      <el-table-column
        prop="assetCode"
        label="资产编号"
        width="230"
        show-overflow-tooltip
      />

      <el-table-column
        prop="address"
        label="资产地址"
        show-overflow-tooltip
        width="200"
      />

      <el-table-column
        prop="originalUnit"
        label="资产权利人"
        show-overflow-tooltip
        width="200"
      />

      <el-table-column
        prop="companyName"
        label="管理单位"
        show-overflow-tooltip
        width="200"
      />

      <el-table-column
        prop="managerName"
        label="资产经办人"
        show-overflow-tooltip
        width="100"
      />

      <el-table-column prop="count" label="资产数量" width="100">
        <template #default="{ row }">
          {{ row.count }}{{ getAssetUnit(row.type) }}
        </template>
      </el-table-column>
      <el-table-column prop="type" label="资产类型" width="100" />
      <!-- <el-table-column prop="rentStatus" label="租赁状态" /> -->
      <el-table-column label="资产文件" show-overflow-tooltip width="150">
        <template #default="{ row }">
          <div class="file-links">
            <template
              v-if="
                row.tenderDocUrl || row.contractDocUrl || row.evaluationDocUrl
              "
            >
              <template v-if="row.tenderDocUrl">
                <el-link
                  type="primary"
                  :underline="false"
                  class="file-link"
                  :href="row.tenderDocUrl"
                  target="_blank"
                >
                  招标
                </el-link>
              </template>
              <template v-if="getUrlList(row.contractDocUrl).length">
                <template
                  v-for="(url, idx) in getUrlList(row.contractDocUrl)"
                  :key="url"
                >
                  <el-link
                    type="primary"
                    :underline="false"
                    class="file-link"
                    :href="url"
                    target="_blank"
                  >
                    合同{{
                      getUrlList(row.contractDocUrl).length > 1 ? idx + 1 : ""
                    }}
                  </el-link>
                  <span
                    v-if="idx !== getUrlList(row.contractDocUrl).length - 1"
                    class="file-separator"
                  >
                    |
                  </span>
                </template>
              </template>
              <template v-if="row.evaluationDocUrl">
                <span
                  v-if="row.tenderDocUrl || row.contractDocUrl"
                  class="file-separator"
                  >|</span
                >
                <el-link
                  type="primary"
                  :underline="false"
                  class="file-link"
                  :href="row.evaluationDocUrl"
                  target="_blank"
                >
                  评估
                </el-link>
              </template>
            </template>
            <span v-else>--</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="预警分析" show-overflow-tooltip width="180">
        <template #default="{ row }">
          <div
            class="warning-status"
            style="display: flex; flex-wrap: wrap; gap: 8px"
          >
            <template v-if="row.warningType">
              <el-tag
                v-for="(text, idx) in row.warningType.split(';')"
                :key="idx"
                size="small"
                effect="light"
                :style="getWarningTagStyleByText(text)"
                @click.stop="handleWarningClickByText(text, row)"
              >
                {{ getWarningTextByText(text) }}
              </el-tag>
            </template>
            <span v-else>--</span>
          </div>
        </template>
      </el-table-column>

      <!-- 轻微、中等、严重 -->
      <!-- <el-table-column prop="countDocumentWarningLevel" label="预警等级">
        <template #default="{ row }">
          <el-tag
            v-if="row?.warningType && row.warningType.includes('合同合规')"
            :type="getLevelTagType(row.countDocumentWarningLevel)"
            disable-transitions
            style="margin-right: 2px"
          >
            {{ row.countDocumentWarningLevel || "--" }}
          </el-tag>

          <el-tag
            v-if="row?.warningType && row.warningType.includes('价格比对')"
            :type="getLevelTagType(row.priceWarningLevel)"
            disable-transitions
          >
            {{ row.priceWarningLevel || "--" }}
          </el-tag>
        </template>
      </el-table-column> -->

      <!-- 推送成功 未推送 推送失败 -->
      <!-- <el-table-column prop="pushStatus" label="推送状态" /> -->
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <span class="total-count">总共 {{ total }} 个项目</span>
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 30, 50]"
        :total="total"
        layout="prev, pager, next, jumper, sizes"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 资产抽屉 -->
    <asset-drawer
      v-model:visible="drawerVisible"
      :type="drawerType"
      :asset-data="currentAssetData"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import AssetDrawer from "./components/AssetDrawer.vue";
import {
  getAssetInfoList,
  getRentPriceComparison,
  getDocumentReviewInfoByAssetCode,
} from "./services";
import { useRoute, useRouter } from "vue-router";

const route = useRoute();
const router = useRouter();

// 搜索表单数据
const searchForm = reactive({
  project: "",
  address: "",
  warningType: "",
  assetCode: "",
  countMin: null,
  countMax: null,
});

// 表格数据
const tableData = ref([]);
const total = ref(0);

// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);

// 抽屉控制
const drawerVisible = ref(false);
const drawerType = ref("");
const currentAssetData = ref(null);

const loading = ref(false);

// 新增：同步URL参数到searchForm和分页
const initFromUrl = () => {
  const query = route.query;
  let hasAdvanced = false;
  Object.keys(searchForm).forEach((key) => {
    if (query[key] !== undefined && query[key] !== null && query[key] !== "") {
      // 数字类型转换
      if (["countMin", "countMax"].includes(key)) {
        searchForm[key] = query[key] === undefined ? null : Number(query[key]);
      } else {
        searchForm[key] = query[key];
      }
      // 检查是否有高级搜索字段
      if (["assetCode", "countMin", "countMax"].includes(key)) {
        hasAdvanced = true;
      }
    }
  });
  if (query.page) currentPage.value = Number(query.page);
  if (query.pageSize) pageSize.value = Number(query.pageSize);
  // 如果有高级搜索字段且有值，则展开高级搜索
  if (hasAdvanced) {
    showAdvanced.value = true;
  }
};

// 新增：同步searchForm和分页到URL
const syncUrl = () => {
  const query = {
    ...searchForm,
    page: currentPage.value,
    pageSize: pageSize.value,
  };
  // 移除空值字段
  Object.keys(query).forEach((key) => {
    if (query[key] === null || query[key] === "") delete query[key];
  });
  router.replace({ query });
};

// 获取表格数据
const fetchTableData = async () => {
  loading.value = true;
  try {
    const res = await getAssetInfoList({
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      ...searchForm,
    });
    tableData.value = res.rows || [];
    total.value = res.total || 0;
  } catch (e) {
    tableData.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  initFromUrl();
  fetchTableData();
});

// 打开抽屉
const openDrawer = async (type, row) => {
  console.log("Opening drawer:", type, row);
  drawerType.value = type;

  // 根据不同类型准备不同的数据
  if (type === "price") {
    try {
      currentAssetData.value = await getRentPriceComparison(row.id);
    } catch (error) {
      console.error("Failed to fetch price comparison data:", error);
      // Handle error appropriately
    }
  } else if (type === "contract") {
    try {
      const contractData = await getDocumentReviewInfoByAssetCode(
        row.assetCode
      );

      currentAssetData.value = {
        contractData: contractData.data.results,
        baseInfo: {
          project: row.project,
          assetCode: row.assetCode,
          address: row.address,
          count: row.count,
        },
      };
    } catch (error) {
      currentAssetData.value = {
        baseInfo: {
          project: row.project,
          assetCode: row.assetCode,
          address: row.address,
          count: row.count,
        },
        data: {},
      };
      // 可选：提示用户接口异常
    }
  } else if (type === "vacancy") {
  }

  currentAssetData.value = {
    ...currentAssetData.value,
    baseInfo: {
      project: row.project,
      assetCode: row.assetCode,
      address: row.address,
      count: row.count,
    },
  };

  drawerVisible.value = true;
  console.log(" currentAssetData.value======", currentAssetData.value);
};

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1;
  syncUrl();
  fetchTableData();
};

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val;
  syncUrl();
  fetchTableData();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  syncUrl();
  fetchTableData();
};

// 获取租赁状态标签类型
const getRentStatusType = (status) => {
  const types = {
    已出租: "success",
    部分出租: "warning",
    空置: "info",
    自用: "primary",
  };
  return types[status] || "info";
};

// 获取预警标签类型
const getWarningTagType = (type) => {
  const types = {
    price: "success",
    contract: "warning",
    vacancy: "info",
  };
  return types[type] || "info";
};

// 获取标签文本
const getWarningText = (type) => {
  const map = {
    price: "价格比对",
    contract: "合同合规",
    vacancy: "空置监测",
    noContract: "无合同",
  };
  return map[type] || type;
};

// 获取预警标签样式
const getWarningTagStyle = (type) => {
  const styleMap = {
    price: {
      color: "#409EFF",
      background: "#E6F0FE",
      borderColor: "#409EFF",
      cursor: "pointer",
    },
    contract: {
      color: "#22C55E",
      background: "#E6F9F0",
      borderColor: "#22C55E",
      cursor: "pointer",
    },
    vacancy: {
      color: "#F59E42",
      background: "#FFF7E6",
      borderColor: "#F59E42",
      cursor: "pointer",
    },
    noContract: {
      color: "#F87171",
      background: "#FEECEC",
      borderColor: "#F87171",
      cursor: "not-allowed",
    },
  };
  return styleMap[type] || {};
};

// 获取预警标签点击处理
const handleWarningClick = (type, row) => {
  if (type === "noContract") return;
  openDrawer(type, row);
};

// 根据中文内容映射到英文key
const warningTextMap = {
  空置: "vacancy",
  合同合规: "contract",
  价格比对: "price",
  价格比对: "price",
  无合同: "noContract",
};

const getWarningTextByText = (text) => {
  const map = {
    price: "价格比对",
    contract: "合同合规",
    vacancy: "空置监测",
    noContract: "无合同",
  };
  const key = warningTextMap[text] || text;
  return map[key] || text;
};

const getWarningTagStyleByText = (text) => {
  const styleMap = {
    price: {
      color: "#409EFF",
      background: "#E6F0FE",
      borderColor: "#409EFF",
      cursor: "pointer",
    },
    contract: {
      color: "#22C55E",
      background: "#E6F9F0",
      borderColor: "#22C55E",
      cursor: "pointer",
    },
    vacancy: {
      color: "#F59E42",
      background: "#FFF7E6",
      borderColor: "#F59E42",
      cursor: "pointer",
    },
    noContract: {
      color: "#F87171",
      background: "#FEECEC",
      borderColor: "#F87171",
      cursor: "not-allowed",
    },
  };
  const key = warningTextMap[text] || text;
  return styleMap[key] || {};
};

const handleWarningClickByText = (text, row) => {
  const key = warningTextMap[text] || text;
  if (key === "noContract") return;
  openDrawer(key, row);
};

const getFirstUrl = (url) => {
  if (!url) return "";
  // 如果是以 [ 开头且包含 http
  if (typeof url === "string" && url.startsWith("[") && url.includes("http")) {
    // 用正则提取第一个 http(s) 链接
    const match = url.match(/https?:\/\/[^\],\s]+/);
    if (match) return match[0];
  }
  return url;
};

const getUrlList = (url) => {
  if (!url) return [];
  if (typeof url === "string" && url.startsWith("[") && url.includes("http")) {
    // 提取所有 http(s) 链接
    return url.match(/https?:\/\/[^\],\s]+/g) || [];
  }
  if (typeof url === "string" && url.startsWith("http")) {
    return [url];
  }
  return [];
};

const getAssetUnit = (type) => {
  if (!type) return "㎡";
  const typeMap = {
    房屋资产: "㎡",
    土地资产: "㎡",
    车位资产: "个",
    其他资产: "个",
  };
  return typeMap[type] || "㎡";
};

const getLevelTagType = (level) => {
  if (level === "轻微") return "primary";
  if (level === "中等") return "warning";
  if (level === "严重") return "danger";
  return "";
};
</script>

<style lang="scss" scoped>
.asset-list-container {
  padding: 20px;
  background: #fff;

  .search-form {
    width: 100%;
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    .el-form-item {
      margin-right: 24px;
      margin-bottom: 12px;
    }
    .el-form-item:last-child {
      margin-right: 0 !important;
    }
  }

  .advanced-form {
    margin-bottom: 16px;
    padding: 16px;
    background: #f5f7fa;
    border-radius: 4px;

    .count-input {
      width: 120px;
    }

    .separator {
      margin: 0 8px;
    }

    .unit {
      margin-left: 8px;
      color: #909399;
    }
  }

  .file-links {
    display: flex;
    gap: 8px;
    align-items: center;

    .file-link {
      font-size: 13px;
      cursor: pointer;

      &:hover {
        opacity: 0.85;
      }

      &.separator::after {
        content: "|";
        margin-left: 8px;
        color: #dcdfe6;
        cursor: default;
      }
    }
  }

  .warning-status {
    display: flex;
    gap: 8px;
    flex-wrap: wrap;

    .warning-tag {
      margin-right: 0;
      cursor: pointer;

      &:hover {
        opacity: 0.85;
      }
    }
  }

  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .total-count {
      color: #606266;
      font-size: 13px;
    }
  }

  :deep(.el-table) {
    .warning-status,
    .file-links {
      .el-tag,
      .el-link {
        cursor: pointer;

        &:hover {
          opacity: 0.85;
        }
      }
    }
  }
}
</style>
